//
//  Groups+Groups.m
//  ClinicalCollections
//
//  Created by janakiraman gopinath on 2/10/13.
//  Copyright (c) 2013 GOPI. All rights reserved.
//

#import "Groups+Groups.h"

@implementation Groups (Groups)
+ (void) groups:(NSArray *) groupList
             withType:(NSString *) type
usingGroupTypes:(GroupTypes *) groupTypes
usingClinicalTrialGov:(ClinicalTrialGov *) clinicalTrialGov
         usingContext:(NSManagedObjectContext *) context
         usingResults:results
{
    if ([groupList isEqual:[NSNull null]])
        return;
    
    for (int i = 0; i < groupList.count; i++) {
        Groups  *groups = (Groups *)[NSEntityDescription insertNewObjectForEntityForName:@"Groups"
                                                                  inManagedObjectContext:context];
        groups.groupId = [groupList[i] valueForKeyPath:@"attributes.group_id"];
        if (![[groupList[i] valueForKey:@"title"] isEqual:[NSNull null]])
            groups.title = [groupList[i] valueForKey:@"title"];
        
        if (![[groupList[i] valueForKey:@"description"] isEqual:[NSNull null]])
            groups.desc = [groupList[i] valueForKey:@"description"];
        
        groups.type = type;
        groups.groupTypes = groupTypes;
        groups.clinicalTrialGov = clinicalTrialGov;
        
    }
    //NSLog(@"Groups Inserted %d Groups...", groupList.count);
    return;
}


+ (Groups *) getGroup:(NSString *)groupId
usingClinicalTrialGov:(ClinicalTrialGov *) clinicalTrialGov
         usingContext:(NSManagedObjectContext *) context
{
    
    NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Groups"];
    request.predicate = [NSPredicate predicateWithFormat:@"groupId = %@ and clinicalTrialGov=%@", groupId, clinicalTrialGov];
    NSSortDescriptor *sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"groupId" ascending:YES];
    request.sortDescriptors = [NSArray arrayWithObject:sortDescriptor];
    Groups *group;
    
    NSError *error = nil;
    NSArray *groups = [context executeFetchRequest:request error:&error];

    if (!groups) {
    } else if (![groups count]) {
        NSLog(@"No data found");
    } else {
        group = [groups lastObject];
        
    }
    return group;
}
@end
